﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.ServiceProcess;
using System.Text;
using System.Configuration;
using System.Threading;
using System.IO;

namespace StockDataCollecter
{
    public partial class StockDataCollectService : ServiceBase
    {
        public StockDataCollectService()
        {
            InitializeComponent();
            
        }

        Timer t = null;
        SinaStockDataHelper stockHelper;
        MySQLAgent o = null;
        protected override void OnStart(string[] args)
        {
            WriteErrLog("I am starting now!" + "\n");
            stockHelper = new SinaStockDataHelper();
            o = stockHelper.GetOraAgent();
            t = new Timer(t_Tick, null, 0, 1000 * 60 * 3);
        }

        protected override void OnStop()
        {
        }

        void WriteErrLog(string err)
        {
            string logPath = ConfigurationManager.AppSettings["logPath"];
            FileStream fs = new FileStream(logPath, FileMode.OpenOrCreate, FileAccess.Write);
            StreamWriter m_streamWriter = new StreamWriter(fs);
            m_streamWriter.BaseStream.Seek(0, SeekOrigin.End);
            m_streamWriter.WriteLine(DateTime.Now.ToString() + "  " + err + "\n");
            m_streamWriter.Flush();
            m_streamWriter.Close();
            fs.Close();
        }

        void t_Tick(object state)
        {
            try
            {
                DateTime now = DateTime.Now;
                WriteErrLog(now.ToString() + "\r" + "start collect:" + "\n");
                SinaStockDataHelper stockHelper = new SinaStockDataHelper();

                string sql = "select * from conf_stock";
                DataTable dtStock = o.ExeQuery(sql);
                for (int i = 0; i < dtStock.Rows.Count; i++)
                {
                    string stockCode = dtStock.Rows[i]["stockcode"].ToString();
                    string stockName = dtStock.Rows[i]["stockname"].ToString();
                    Stock s = stockHelper.GetStockInfoByCode(stockCode);
                    if (s == null) continue;
                    s.StockName = stockName;
                    if (ValidateInCollertTime(now))
                    {
                        string sqlinsert = "insert into perf_stock values (" +
                        "'{0}','{1}','{2}','{3}','{4}','{5}','{6}','{7}','{8}','{9}','{10}'," +
                        "'{11}','{12}','{13}','{14}','{15}','{16}','{17}','{18}','{19}','{20}'," +
                        "'{21}','{22}','{23}')";
                        sqlinsert = string.Format(sqlinsert, s.StockCode, s.StockName, s.StockTime,
                            s.LastPrice, s.InflationFallNumber,
                            s.LowestPrice, s.HighestPrice, s.InflationFallPercent, s.Cjl, s.Cje,
                            s.JmjIn, s.JmjOut, s.DelegatePercent, s.Min1, s.Min2, s.Min3, s.Min4, s.Min5,
                            s.MOut1, s.MOut2, s.MOut3, s.MOut4, s.MOut5, now);
                        o.ExeQuery(sqlinsert);
                    }
                    if (now.Hour == 16)
                    {
                        string collectDate = now.ToShortDateString();
                        string existsD = string.Format("select * from perf_stock_d where starttime='{0}' and stockcode='{1}'",
                            collectDate, s.StockCode);
                        if (o.ExeQuery(existsD).Rows.Count == 0)
                        {
                            string sqlinsertD = "insert into perf_stock_d values (" +
                            "'{0}','{1}','{2}','{3}','{4}','{5}','{6}','{7}','{8}','{9}','{10}')";
                            sqlinsertD = string.Format(sqlinsertD, s.StockCode, s.StockName, collectDate,
                            s.YesterdayEndPrice, s.TodayStartPrice, s.LowestPrice, s.HighestPrice,
                            s.InflationFallNumber, s.InflationFallPercent, s.Cjl, s.Cje);
                            o.ExeQuery(sqlinsertD);
                        }
                    }
                }
                WriteErrLog(DateTime.Now.ToString() + "\r" + "end collect!" + "\n");
            }
            catch (Exception ex)
            {
                WriteErrLog(ex.Message + "\r" + ex.StackTrace);
            }
        }
        private bool ValidateInCollertTime(DateTime now)
        {
            int y = now.Year;
            int m = now.Month;
            int d = now.Day;
            DateTime dt1 = new DateTime(y, m, d, 9, 25, 0);
            DateTime dt2 = new DateTime(y, m, d, 11, 35, 0);
            DateTime dt3 = new DateTime(y, m, d, 13, 0, 0);
            DateTime dt4 = new DateTime(y, m, d, 15, 10, 0);
            if ((now >= dt1 && now < dt2) || (now >= dt3 && now < dt4))
                return true;
            return false;
        }
    }
}